package persistencia;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class AdministradorDeConexion{
	
	private String server="";
	private String user="";
	private String password="";
	private String driver="";
	private static AdministradorDeConexion instancia;
	boolean isWindows = OSValidator.isWindows();

	//**********************************************************************************************************************************************//
	// CONEXION -- GRACIAS!!!!
	//**********************************************************************************************************************************************//
	
	private AdministradorDeConexion(){
	}
	
	public static AdministradorDeConexion getInstancia() {
		if(instancia == null)
			return instancia = new AdministradorDeConexion();
		return instancia;
	}
	
	public Connection connect() {
		
		if (isWindows) {
			
			// Microsoft SQL Server Settings.
			
			server	 = "jdbc:sqlserver://127.0.0.1:1433";
			user	 = "uraices";
			password = "uraices";
			driver	 = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
			
		}
		else {

			// MySQL Settings.
			
			server	 = "jdbc:mysql://127.0.0.1:3306/Raices";
			user	 = "root";
			password = "";
			driver	 = "com.mysql.jdbc.Driver";
		}
		
		try {
			Class.forName(driver);
			Connection connection = DriverManager.getConnection(server, user, password);
			if (connection != null){
				System.out.println("Info: PoolConnection.connect(): Conexion con el Servidor de Base de Datos Exitosa." + server);
				return connection;
			}
			else {
				System.out.println("Error: PoolConnection.connect(): No se pudo Establecer Conexion con el Servidor de Base de Datos: " + server);
			}	
		}
		catch (ClassNotFoundException e) {
			System.out.println("Error: PoolConnection.connect(): No se Pudo Encontrar el Driver de la Base de Datos. " + e.getLocalizedMessage());
		}
		catch (SQLException e) {
			System.out.println("Error: PoolConnection.connect(): Error al Conectar con la Base de Datos. " + e.getLocalizedMessage());
		}
		catch (Exception e) {
			System.out.println("Error: PoolConnection.connect(): Error Generico de Base de Datos. " + e.getLocalizedMessage());
		}
		return null;
	}
	
	//**********************************************************************************************************************************************//
	// DESCONEXION
	//**********************************************************************************************************************************************//
	
	public void closeConnection(Connection conn){
		try {
			conn.close();
		} catch (SQLException e) {
			System.out.println("PoolConnection.closeConnection(): Error al Intentar Finalizar la Conexion con la Base de Datos.");
		}
	}
	
}
